import itchat
import time
import os
import sys
import platform
from itchat.content import TEXT
from loguru import logger
from glm_api import GLMBot
from config import WECHAT_CONFIG, LOG_CONFIG

# 配置日志
logger.configure(
    handlers=[
        # 文件日志
        {
            "sink": "logs/bot.log",
            "rotation": LOG_CONFIG["rotation"],
            "format": LOG_CONFIG["format"],
            "level": LOG_CONFIG["level"],
        },
        # 终端日志
        {
            "sink": sys.stdout,
            "format": "<green>{time:HH:mm:ss}</green> | <level>{level: <8}</level> | <white>{message}</white>",
            "level": "INFO",
            "colorize": True,
        }
    ]
)

class WeChatBot:
    def __init__(self):
        self.glm = GLMBot()
        
    def handle_private_msg(self, msg):
        """处理私聊消息"""
        try:
            if msg['FromUserName'] in WECHAT_CONFIG['blocked_users']:
                logger.info("消息来自被屏蔽用户，已忽略")
                return
            
            sender = msg['FromUserName']
            content = msg['Text']
            
            logger.info(f"收到私聊消息 - 发送者: {sender}")
            logger.info(f"消息内容: {content}")
            
            time.sleep(WECHAT_CONFIG['reply_delay'])
            reply = self.glm.chat(content)
            
            itchat.send(reply, toUserName=sender)
            logger.info(f"回复内容: {reply}")
            
        except Exception as e:
            error_msg = f"处理私聊消息时出错: {str(e)}"
            logger.error(error_msg)
            logger.exception(e)

    def handle_group_msg(self, msg):
        """处理群聊消息"""
        try:
            if msg['FromUserName'] in WECHAT_CONFIG['blocked_groups']:
                logger.info("消息来自被屏蔽群组，已忽略")
                return
            
            group_id = msg['FromUserName']
            sender = msg['ActualNickName']
            content = msg['Text']
            
            should_reply = (not WECHAT_CONFIG['group_reply_mention']) or msg['IsAt']
            
            if should_reply:
                logger.info(f"收到群聊消息 - 群: {group_id}, 发送者: {sender}")
                logger.info(f"消息内容: {content}")
                
                if msg['IsAt']:
                    pure_content = content.replace('@' + msg['User']['Self']['NickName'], '')
                    logger.debug(f"去除@后的内容: {pure_content}")
                else:
                    pure_content = content
                    
                time.sleep(WECHAT_CONFIG['reply_delay'])
                reply = self.glm.chat(pure_content)
                
                response = f"@{sender}\n{reply}"
                itchat.send(response, toUserName=group_id)
                logger.info(f"回复内容: {response}")
                
        except Exception as e:
            error_msg = f"处理群聊消息时出错: {str(e)}"
            logger.error(error_msg)
            logger.exception(e)

    def run(self):
        """运行机器人"""
        @itchat.msg_register([TEXT])
        def private_msg(msg):
            self.handle_private_msg(msg)

        @itchat.msg_register([TEXT], isGroupChat=True)
        def group_msg(msg):
            self.handle_group_msg(msg)

        try:
            logger.info("正在启动微信机器人...")
            # Windows使用图片文件显示二维码，Linux使用小号彩色二维码
            qr_value = False if platform.system() == 'Windows' else 0
            itchat.auto_login(
                hotReload=True,
                enableCmdQR=qr_value,
                loginCallback=lambda: logger.info("登录成功！"),
                exitCallback=lambda: logger.info("已退出登录。")
            )
            logger.info("微信机器人已启动")
            logger.info("等待消息中...")
            itchat.run()
            
        except Exception as e:
            error_msg = f"启动失败: {str(e)}"
            logger.error(error_msg)
            logger.exception(e)
            logger.info("请确保已经安装了最新版的 itchat-uos")

if __name__ == '__main__':
    # 显示启动界面
    startup_banner = """
     ██████╗ ███████╗      ██████╗██╗  ██╗ █████╗ ████████╗
    ██╔═══██╗╚══███╔╝     ██╔════╝██║  ██║██╔══██╗╚══██╔══╝
    ██║   ██║  ███╔╝█████╗██║     ███████║███████║   ██║   
    ██║▄▄ ██║ ███╔╝ ╚════╝██║     ██╔══██║██╔══██║   ██║   
    ╚██████╔╝███████╗     ╚██████╗██║  ██║██║  ██║   ██║   
     ╚══▀▀═╝ ╚══════╝      ╚═════╝╚═╝  ╚═╝╚═╝  ╚═╝   ╚═╝   
    ════════════════════════════════════════════════════════
                Powered by GLM-4 API  v1.0.0
    """
    print(startup_banner)
    print("\n正在初始化机器人...\n")
    
    if not os.path.exists('logs'):
        os.makedirs('logs')
    
    bot = WeChatBot()
    bot.run() 